package com.zhiyin.game.Service;

import com.alibaba.fastjson.JSONObject;
import com.zhiyin.game.bean.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class BankService {

    private Logger logger = LoggerFactory.getLogger(BankService.class);

    /**
     * 填充银行的数据
     *
     * @param bankSize  生成银行数量
     * @param map 地图数据
     * @return
     */
    public Cell[][] initBankData(int bankSize, Cell[][] map) {
        List<String> bankLocations = new ArrayList<>();
        List<Integer> marks = new ArrayList<>();
        List<Integer> xList = new ArrayList<>();
        List<Integer> yList = new ArrayList<>();
        int xSize = map.length;
        int ySize = map[0].length;
        for (int i = 1; i < xSize-1; i++) {
            xList.add(i);
        }
        for (int i = 1; i < ySize-1; i++) {
            yList.add(i);
        }
        String location = "";
        int maxRandom = 100;
        int i = 0;
        do{
            int x = xList.get((int)(Math.random()*xList.size()));
            int y = yList.get((int)(Math.random()*yList.size()));
            location = x + "," + y;
            int mark = 10 + (int)(Math.random()*90);
            while (marks.contains(mark)){
                mark = 10 + (int)(Math.random()*90);
            }
            if (!judgeInstance(bankLocations,location)){
                marks.add(mark);
                bankLocations.add(location);
                map[x][y].setMark(mark);
                xList.remove(xList.indexOf(x));
                yList.remove(yList.indexOf(y));
            }
            i ++ ;
        }
        while (bankLocations.size() < bankSize && judgeInstance(bankLocations,location) &&
                i < maxRandom && xList.size() > 0 && yList.size() > 0);
        System.out.println(JSONObject.toJSON(bankLocations));
        return map;
    }

    public Boolean judgeInstance(List<String> bankLocations,String location){
        int newX =  Integer.parseInt(location.split(",")[0]);
        int newY =  Integer.parseInt(location.split(",")[1]);
        if (bankLocations.size() > 0){
            for (String bankLocation : bankLocations){
                int oldX = Integer.parseInt(bankLocation.split(",")[0]);
                int oldY = Integer.parseInt(bankLocation.split(",")[1]);
                if (newX == oldX || newY == oldY ||
                    ((int)Math.pow(Math.abs(newX-oldX),2) + (int)Math.pow(Math.abs(newY-oldY),2)) < 16){
                    return true;
                }
            }
        }
        return false;
    }
}
